/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import collection.Products;
import com.opensymphony.xwork2.ActionContext;
import dto.Product;
import dto_pakinfo.User;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;

/**
 *
 * @author duonghung1369
 */
public class ServerValidation {

    public enum Role {

        GUEST, CUSTOMER, ADMIN
    }
    private static Role current_role = Role.GUEST;

    public static Map validateRegister(User user) {
        Map errors = new HashMap<String, String>();
        if (user.getUsername().length() < 6 || user.getUsername().length() > 30) {
            errors.put("username", "Username must be 6 - 30 characters in length!");
        }

        if (user.getPassword().length() < 6 || user.getPassword().length() > 30) {
            errors.put("password", "Password must be 6 - 30 characters in length!");
        }

        if (user.getProfile().getFirstname().length() == 0) {
            errors.put("firstname", "First name not be blank!");
        }

        if (user.getProfile().getLastname().length() == 0) {
            errors.put("lastname", "Last name not be blank!");
        }

        if (user.getProfile().getEmail().length() == 0) {
            errors.put("email", "Email not be blank!");
        }

        if (user.getProfile().getAddress().length() == 0) {
            errors.put("address", "Address not be blank!");
        }

        return errors;
    }

    public static List validateCheckoutProcesscing(Products clientItems, Products serverItems) {
        Product tmpServer;
        List<String> errors = new ArrayList<String>();
        for (Product clientItem : clientItems.getProducts()) {
            tmpServer = serverItems.contains(clientItem.getId());
            if (tmpServer != null) {
                if (tmpServer.getQuantity() < clientItem.getQuantity()) {
                    errors.add("Some items of product: <span style=\"color: blue;\">\"" + tmpServer.getName()
                            + "\"</span> have just been sold, now just only has <span style=\"font-size: 20px;\">" + tmpServer.getQuantity() + "</span> item(s) in stock! Please update quantity in your cart before checkout!");
                }
                
                if(tmpServer.isIsDeleted()) {
                    errors.add("Product: <span style=\"color: blue;\">\"" + tmpServer.getName()
                            + "\"</span> has been deleted by administrator and not available for sale anymore! Please remove this product in your cart and comeback to home page"
                            + " to get new updated products!");
                }
            }
        }

        return errors;
    }

    public static boolean isGuest() {
        updateRole();
        // check to store last url just before go to login page
        if (current_role == Role.GUEST) {
            HttpServletRequest request = ServletActionContext.getRequest();
            String url = request.getRequestURI();
            String subUrl = url.substring(nthIndexOf(url, "/", 1));

            Map session = ActionContext.getContext().getSession();
            session.put(StringUtil.LASTURL, subUrl);
            return true;
        }
        return false;
    }

    public static boolean isCustomer() {
        updateRole();
        return (current_role == Role.CUSTOMER);
    }

    public static boolean isAdmin() {
        updateRole();
        return (current_role == Role.ADMIN);
    }

    public static void updateRole() {
        Map session = ActionContext.getContext().getSession();
        Object obj = session.get(StringUtil.ISADMIN);
        if (obj == null) { // not logined yet
            current_role = Role.GUEST;
            return;
        }

        Boolean isAdmin = (Boolean) obj;
        if (isAdmin) {
            current_role = Role.ADMIN;
        } else {
            current_role = Role.CUSTOMER;
        }
    }

    /**
     * Get stored last url from session.
     * @return url if url not null, DEFAULT_PATH otherwise.
     */
    public static String getLastURL() {
        Map session = ActionContext.getContext().getSession();
        Object url = session.get(StringUtil.LASTURL);

        if (url != null) {
            return (String) url;
        }

        return StringUtil.DEFAULT_URL;

    }

    /**
     * Return the <i>nth</i> index of the given token occurring in the given string.
     *
     * @param string     String to search.
     * @param token      Token to match.
     * @param index      <i>Nth</i> index.
     * @return           Index of <i>nth</i> item or -1.
     */
    public static int nthIndexOf(final String string, final String token,
            final int index) {
        int j = 0;

        for (int i = 0; i < index; i++) {
            j = string.indexOf(token, j + 1);
            if (j == -1) {
                break;
            }
        }

        return j;
    }
}
